<script lang="jsx" setup>
import { nextTick, ref } from 'vue';
import { CheckCircleOutlined, StopOutlined, SwapOutlined } from '@ant-design/icons-vue';
import { getAllForms } from '@/service/api/modules/check-inventory-manage/form-setup';
import {
  addDevice,
  disableDelete,
  editDevice,
  enableDelete
} from '@/service/api/modules/check-inventory-manage/device-setup';
import Add from './modules/add.vue';

const commonSearchRef = ref(null);
const tableRef = ref(null);

const formList = ref([]);

const searchParams = ref({
  form: null,
  inspectionMachineName: null,
  inspectionMachineNo: null,
  inspectionFormId: null,
  delFlag: '0'
});
const searchFormList = [
  {
    type: 'select',
    key: 'form',
    label: '关联表单',
    placeholder: '请输入关联表单',
    span: 24,
    md: 12,
    lg: 5,
    xl: 5,
    xxl: 4,
    search: true,
    selectOptions: formList,
    change(val) {
      searchParams.value.inspectionFormId = formList.value.find(item => item.value === val).id;
    }
  },
  {
    type: 'input',
    key: 'inspectionMachineName',
    label: '设备名称',
    placeholder: '请输入设备名称',
    span: 24,
    md: 12,
    lg: 5,
    xl: 5,
    xxl: 4
  },
  {
    type: 'input',
    key: 'inspectionMachineNo',
    label: '机台号',
    placeholder: '请输入机台号',
    span: 24,
    md: 12,
    lg: 5,
    xl: 5,
    xxl: 4
  },
  {
    type: 'select',
    key: 'delFlag',
    label: '状态',
    placeholder: '请选择状态',
    span: 24,
    clear: false,
    md: 12,
    lg: 5,
    xl: 5,
    xxl: 4,
    selectOptions: [
      {
        label: '启用',
        value: '0'
      },
      {
        label: '禁用',
        value: '1'
      }
    ],
    change() {
      search();
    }
  }
];

const column = ref([
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inspectionMachineName',
    dataIndex: 'inspectionMachineName',
    title: '设备名称',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inspectionMachineCode',
    dataIndex: 'inspectionMachineCode',
    title: '设备编号',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inspectionMachineDept',
    dataIndex: 'inspectionMachineDept',
    title: '部门',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inspectionMachineNo',
    dataIndex: 'inspectionMachineNo',
    title: '机台号',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inspectionFormName',
    dataIndex: 'inspectionFormName',
    title: '关联表单',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'delFlag',
    dataIndex: 'delFlag',
    title: '状态',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return (
        <span class={record.delFlag === '0' ? 'color-green' : 'color-red'}>{['启用', '禁用'][record.delFlag]}</span>
      );
    }
  },
  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '创建人',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createDate',
    dataIndex: 'createDate',
    title: '创建时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'updateDate',
    dataIndex: 'updateDate',
    title: '修改时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'updateBy',
    dataIndex: 'updateBy',
    title: '修改人',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  }
]);

async function getFormOptions() {
  const { data, error } = await getAllForms();
  if (!error) {
    formList.value = data.map(item => ({
      ...item,
      label: item.inspectionFormName,
      value: item.inspectionFormName
    }));
  }
}

getFormOptions();

function search() {
  tableRef.value.getData(1);
}

function reset() {
  nextTick(() => {
    searchParams.value = {
      inspectionMachineName: null
    };
    search();
  });
}

const selectedRow = ref([]);
const currentRow = ref(null);
function tableSelectChange(data) {
  selectedRow.value = data;
}
const operationType = ref('add');
const addRef = ref(null);
const { handleShow, handleLoading, updateModalOptions, handleClose } = window.$useModal({
  modalOption: {
    title: `新增检查项`,
    destroyOnClose: true,
    height: '430px'
  },
  component: () => (
    <Add
      ref={addRef}
      operationType={operationType.value}
      row-data={currentRow.value}
      formOptions={formList.value}
    ></Add>
  ),
  onOk: async () => {
    const data = { ...addRef.value };
    await data.validateForm();
    handleLoading(true);
    try {
      const formData = { ...data.model };
      let pro;
      if (operationType.value === 'add') {
        pro = await addDevice(formData);
      } else {
        formData.id = currentRow.value.id;
        pro = await editDevice(formData);
      }
      const { error } = await pro;
      if (!error) {
        window.$message.success('操作成功');
        handleClose();
        search();
      }
    } finally {
      handleLoading(false);
    }
  }
});

function handleShowModal(type) {
  operationType.value = type;
  if (type === 'edit') {
    updateModalOptions({
      title: '修改点检设备'
    });
    currentRow.value = selectedRow.value[0];
  }
  if (type === 'add') {
    updateModalOptions({
      title: '新增点检设备'
    });
    currentRow.value = null;
  }
  if (type === 'bindForm') {
    updateModalOptions({
      title: '绑定表单'
    });
    currentRow.value = selectedRow.value[0];
  }
  handleShow();
}

async function handelDelete() {
  const operation = searchParams.value.delFlag === '0' ? '禁用' : '启用';
  if (!selectedRow.value.length) {
    window.$message.error(`请选择需要${operation}的设备!`);
    return;
  }
  window.$modal.confirm({
    title: `确认${operation}设备名称为:"${selectedRow.value.map(item => item.inspectionMachineName).join(',')}"吗?`,
    onOk: async () => {
      const { error } = await (searchParams.value.delFlag === '0'
        ? disableDelete([...selectedRow.value])
        : enableDelete([...selectedRow.value]));
      if (!error) {
        window.$message.success(`${operation}成功`);
        searchParams.value.delFlag = searchParams.value.delFlag === '0' ? '1' : '0';
        search();
      }
    }
  });
}
</script>

<template>
  <div class="device-setup-page jl-main-page min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="commonSearchRef"
      v-model:searchParams="searchParams"
      :form-list="searchFormList"
      :is-search="true"
      @search="search"
      @reset="reset"
    ></CommonSearch>

    <Table
      ref="tableRef"
      v-model:searchParams="searchParams"
      :column="column"
      :show-row-selection="true"
      row-key="tableUuid"
      :scroll="{ y: 'auto' }"
      is-init-get-data
      url="/inspection/inspectionform/selectMachines"
      :auto-generate-uuid="true"
      @table-select-change="tableSelectChange"
    >
      <template #tableTitle>
        <AButton
          v-hasAuth="['check-inventory-manage:device-setup:add']"
          type="primary"
          size="small"
          ghost
          class="mini-btn mr-8px"
          @click="handleShowModal('add')"
        >
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px">新增</span>
        </AButton>
        <AButton
          v-hasAuth="['check-inventory-manage:device-setup:edit']"
          type="primary"
          size="small"
          :disabled="selectedRow.length !== 1"
          ghost
          class="mini-btn mr-8px"
          @click="handleShowModal('edit')"
        >
          <template #icon>
            <icon-ic-round-edit class="align-sub text-icon" />
          </template>
          <span class="ml-3px">修改</span>
        </AButton>
        <AButton
          v-if="searchParams.delFlag == '0'"
          v-hasAuth="['check-inventory-manage:device-setup:change-status']"
          type="primary"
          size="small"
          danger
          :disabled="!selectedRow.length"
          ghost
          class="mini-btn mr-8px"
          @click="handelDelete"
        >
          <template #icon>
            <StopOutlined />
          </template>
          <span class="ml-3px">禁用</span>
        </AButton>
        <AButton
          v-else
          v-hasAuth="['check-inventory-manage:device-setup:change-status']"
          type="primary"
          size="small"
          :disabled="!selectedRow.length"
          ghost
          class="mini-btn mr-8px"
          @click="handelDelete"
        >
          <template #icon>
            <CheckCircleOutlined />
          </template>
          <span class="ml-3px">启用</span>
        </AButton>
        <AButton
          v-hasAuth="['check-inventory-manage:device-setup:bind-form']"
          type="primary"
          size="small"
          :disabled="selectedRow.length !== 1"
          ghost
          class="mini-btn mr-8px"
          @click="handleShowModal('bindForm')"
        >
          <template #icon>
            <SwapOutlined />
          </template>
          <span class="ml-3px">绑定表单</span>
        </AButton>
      </template>
    </Table>
  </div>
</template>

<style lang="scss" scoped></style>
